const fs = require("fs")
///编辑相关接口
module.exports = function (app, models, $, db, nm) {
    //获取真实路径
    function get_file_path(pathname){ 
        let real_key = ''
        if(pathname == '/' || pathname == ''){
            real_key = 'default'
        }else{
            for(let key in Config.router){
                if(new RegExp(key).test(pathname)){
                    real_key = key
                    break
                }
            }
        }
        if(!real_key) return ''
        let html_path = Config.router[real_key].html || Config.router[real_key]
        return __dirname.replace('router',html_path.replace('./',''))
    }
    //获取页面
    app.get('/v1/page',async function(req,res){
        let hash = req.query.hash.replace('#','')
        let pathname = get_file_path(req.query.pathname)
        if(!pathname) return res.send({ errorMsg:'路径错误' })
        let path = pathname + hash + (req.query.type || '.html')
        res.send({ code:fs.readFileSync(path,'utf-8') })
    })
    //修改页面
    app.put('/v1/page',async function(req,res){
        let hash = req.body.hash.replace('#','')
        let pathname = get_file_path(req.body.pathname)
        let code = req.body.code
        if(!pathname) return res.send({ errorMsg:'路径错误' })
        let path = pathname + hash + (req.body.type || '.html')
        fs.writeFileSync(path, code)
        res.send({ message:'修改成功,请刷新页面查看效果' })
    })
}